package com.chapter.sample.jvm.gc;

import java.util.concurrent.TimeUnit;

public class JstackDeadLockDemo {
    private final static Object obj1 = new Object();
    private final static Object obj2 = new Object();

    public static void main(String[] args) {
        new JstackDeadLockDemo().testDeadlock();;
    }

    public void testDeadlock() {
        Thread t1 = new Thread(() -> {
            calLock_Obj1_first();
        });
        Thread t2 = new Thread(() -> {
            calLock_Obj2_first();
        });
        t1.start();
        t2.start();
    }

    public static void calLock_Obj1_first() {
        synchronized (obj1) {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("已经拿到obj1的对象锁，jie下来等待Obj2的对象锁");
            synchronized (obj2) {
                System.out.println("1");
            }
        }
    }
    public static void calLock_Obj2_first() {
        synchronized (obj2) {
            System.out.println("已经拿到obj2的对象锁，jie下来等待Obj1的对象锁");
            System.out.println(1);
            synchronized (obj1) {
                System.out.println(2);
            }
        }
    }
}
